# -*- coding:UTF-8 -*-#

'''
@author: qianwp
'''

from DBUtils.PooledDB import PooledDB
import MySQLdb
from popcan.db.dbbase import BaseDao
from popcan.db.sqls import SQLUID, SQLLogin, SQLCustomer, SQLDesigner, SQLAlbum, SQLComposit, SQLPhoto, SQLComment
from popcan.helper.loggerhelper import QueueLogger, Module
from popcan.helper.datehelper import formatDate
from popcan.core.structures import Singleton
from popcan.model.models import Customer,Designer,Album,Composit,Photo,Comment
from popcan.core.halt import HaltManager,PooldbHaltHooker
from popcan.globals.settings import DBSettings

class DaosLoader(Singleton):
    
    def loadDaos(self):
        QueueLogger().info(Module.Load, 'loading Database Accessors')
        pooldb = PooledDB(creator=MySQLdb,
                          mincached=DBSettings.mincached,
                          maxcached=DBSettings.maxcached,
                          maxusage=DBSettings.maxusage,
                          blocking=True,
                          setsession=['SET AUTOCOMMIT=0', 'SET NAMES UTF8'],
                          host=DBSettings.host,
                          user=DBSettings.user,
                          passwd=DBSettings.passwd,
                          db=DBSettings.db
                          )
        HaltManager().addHooker(PooldbHaltHooker(pooldb))
        UIDDaos(pooldb)
        CustomerDao(pooldb)
        DesignerDao(pooldb)
        AlbumDao(pooldb)
        CompositDao(pooldb)
        PhotoDao(pooldb)
        CommentDao(pooldb)
        QueueLogger().info(Module.Load, 'DB Accessors loaded success')

class UIDDaos(BaseDao):
    
    def getCurCustId(self, minuid, maxuid):
        result = self.queryunique(SQLUID.MaxCustId, (minuid, maxuid))
        return int(result[0]) if result[0] else 0
    
    def getCurAlbumId(self, minuid, maxuid):
        result = self.queryunique(SQLUID.MaxAlbumId, (minuid, maxuid))
        return int(result[0]) if result[0] else 0
    
    def getCurCompstId(self, minuid, maxuid):
        result = self.queryunique(SQLUID.MaxCompstId, (minuid, maxuid))
        return int(result[0]) if result[0] else 0
    
    def getCurPhotoId(self, minuid, maxuid):
        result = self.queryunique(SQLUID.MaxPhotoId, (minuid, maxuid))
        return int(result[0]) if result[0] else 0
    
    def getCurCommentId(self, minuid, maxuid):
        result = self.queryunique(SQLUID.MaxCommentId, (minuid, maxuid))  
        return int(result[0]) if result[0] else 0
    
class CustomerDao(BaseDao):
    
    def existsEmail(self, email):
        result = self.queryunique(SQLLogin.CheckEmail, (email))
        return result[0] > 0
    
    def existsNick(self, nick):
        result = self.queryunique(SQLLogin.CheckNick, (nick))
        return result[0] > 0
    
    def getCustomerByEmail(self,email):
        result = self.queryunique(SQLLogin.GetCustomerByEmail, (email))
        if not result:return None
        customer = Customer()
        customer.fromrow(result)
        return customer
    
    def getCustomerById(self,cust_id):
        result = self.queryunique(SQLLogin.GetCustomerById, (cust_id))
        if not result:return None
        customer = Customer()
        customer.fromrow(result)
        return customer
    
    def validPasswd(self,email,passwd):
        result = self.queryunique(SQLLogin.CheckNick, (email))
        return result[0] > 0
    
    def addCustomer(self, customer):
        self.insert(SQLLogin.AddCustomer, (customer.custId, customer.email, customer.nick, customer.passwd, formatDate(customer.regdate), formatDate(customer.logindate),int(customer.upgraded)))
        return True

    def upgradeCustomer(self,customer):
        self.update(SQLCustomer.UpgradeCustomer, (int(customer.upgraded),customer.custId))
        return True
        
    def updateLoginDate(self,customer):
        self.update(SQLCustomer.UpdateLoginDate, (formatDate(customer.logindate),customer.custId))
        return True
        
    def updatePasswd(self,customer):
        self.update(SQLCustomer.UpdatePasswd, (customer.passwd,customer.custId))
        return True

class DesignerDao(BaseDao):
    
    def addDesigner(self,designer):
        self.insert(SQLDesigner.AddDesigner, (designer.custId, designer.realname,designer.identnum,designer.contactnum,designer.address,formatDate(designer.createdate)))
        return True
        
    def getDesignerById(self,cust_id):
        result = self.queryunique(SQLDesigner.GetDesigner, (cust_id))
        if not result:return None
        designer = Designer()
        designer.fromrow(result)
        return designer
    
class AlbumDao(BaseDao):
    
    def addAlbum(self,album):
        self.insert(SQLAlbum.AddAlbum, (album.albumId,album.custId,album.name,formatDate(album.createdate)))
        return True
    
    def getAlbumById(self,album_id):
        result = self.queryunique(SQLAlbum.GetAlbumById, (album_id))
        if not result:return None
        album = Album()
        album.fromrow(result)
        return album
    
    def getAlbumsByCustId(self,cust_id):
        result = self.querylist(SQLAlbum.GetAlbumsByCustId, (cust_id))
        albums = []
        for each in result:
            album = Album()
            albums.append(album.fromrow(each))
        return albums
    
    def getAlbumIdsByCustId(self,cust_id):
        result = self.querylist(SQLAlbum.GetAlbumIdsByCustId, (cust_id))
        albumIds = []
        for each in result:
            albumIds.append(long(each[0]))
        return albumIds
    
    def removeAlbum(self,album):
        return self.removeAlbumById(album.albumId)
        
    def removeAlbumById(self,albumId):
        self.delete(SQLAlbum.RemoveAlbumById, (albumId))
        return True
    
    def updateAlbumName(self,album):
        self.update(SQLAlbum.UpdateAlbumName, (album.name,album.albumId))
        return True
    
class CompositDao(BaseDao):
    
    def addComposit(self,composit):
        self.insert(SQLComposit.AddComposit, (composit.compositId,composit.name,composit.custId,composit.albumId,formatDate(composit.createdate)))
        return True
    
    def getCompositById(self,compositId):
        result = self.queryunique(SQLComposit.GetCompositById, (compositId))
        if not result:return None
        composit = Composit()
        composit.fromrow(result)
        return composit
    
    def getCompositsByAlbumId(self,albumId):
        result = self.querylist(SQLComposit.GetCompositsByAlbumId, (albumId))
        composits = []
        for each in result:
            composit = Composit()
            composit.fromrow(each)
        return composits
    
    def getCompositIdsByAlbumId(self,albumId):
        result = self.querylist(SQLComposit.GetCompositIdsByAlbumId,(albumId))
        compositIds = []
        for each in result:
            compositIds.append(long(each[0]))
        return compositIds
    
    def removeComposit(self,composit):
        return self.removeCompositById(composit.compositId)
    
    def removeCompositById(self,compositId):
        self.delete(SQLComposit.RemoveCompositById, (compositId))
        return True
    
    def updateCompositName(self,composit):
        self.update(SQLComposit.UpdateCompositName, (composit.name,composit.compositId))
        return True
    
class PhotoDao(BaseDao):
    
    def addPhoto(self,photo):
        self.insert(SQLPhoto.AddPhoto, (photo.photoId,photo.url,photo.createdate,photo.compositId,photo.albumId,photo.custId))
        return True
        
    def getPhotoById(self,photoId):
        result = self.queryunique(SQLPhoto.GetPhotoById, (photoId))
        if not result:return None
        photo = Photo()
        photo.fromrow(result)
        return photo
    
    def getPhotoIdsByCompositId(self,compositId):
        result = self.querylist(SQLPhoto.GetPhotoIdsByCompositId, (compositId))
        photoIds = []
        for each in result:
            photoIds.append(long(each[0]))
        return photoIds
    
    def getPhotosByCompositId(self,compositId):
        result = self.querylist(SQLPhoto.GetPhotosByCompositId,(compositId))
        photos = []
        for each in result:
            photo = Photo()
            photo.fromrow(each)
            photos.append(photo)
        return photos
    
    def removePhotoById(self,photoId):
        self.delete(SQLPhoto.RemovePhotoById, (photoId))
        return True
    
    def removePhoto(self,photo):
        return self.removePhotoById(photo.photoId)
    
    def updatePhotoUrl(self,photo):
        self.update(SQLPhoto.UpdatePhotoUrl, (photo.url,photo.photoId))
        return True
    
class CommentDao(BaseDao):
    
    def addComment(self,comment):
        self.insert(SQLComment.AddComment, (comment.commentId,comment.compositId,comment.conent,comment.fromcustId,formatDate(comment.createdate)))
        return True
    
    def getCommentById(self,commentId):
        result = self.queryunique(SQLComment.GetCommentById, (commentId))
        if not result:return None
        comment = Comment()
        comment.fromrow(result)
        return comment

    def getCommentsByCompositId(self,compositId):
        result = self.querylist(SQLComment.GetCommentIdsByCompositId, (compositId))
        comments = []
        for each in result:
            comment = Comment()
            comment.fromrow(each)
            comments.append(comment)
        return comments
    
    def getCommentIdsByCompositId(self,compositId):
        result = self.querylist(SQLComment.GetCommentIdsByCompositId, (compositId))
        commentIds = []
        for each in result:
            commentIds.append(long(each[0]))
        return commentIds
    
    def removeCommentById(self,commentId):
        self.delete(SQLComment.RemoteCommentById, (commentId))
        return True
    
    def removeComment(self,comment):
        return self.removeCommentById(comment.commentId)
    